import { Component, OnInit, OnDestroy } from "@angular/core";
import { TreeNode } from "./irr-project";
import { MapUiService } from "../map-ui.service";
import { takeUntil } from "rxjs/operators";
import { Subject } from "rxjs";
import {
  LatLonArray,
  OverlayService
} from "unified-map";
import { DialogPumpComponent } from "../dialog-pump/dialog-pump.component";
import { DialogSectionComponent } from "../dialog-section/dialog-section.component";
import { DialogGateComponent } from "../dialog-gate/dialog-gate.component";
import { DialogVideoComponent } from '../dialog-video/dialog-video.component';
import { DialogIntakeComponent } from '../dialog-intake/dialog-intake.component';
import { TypeMapper } from '../one-map';

@Component({
  selector: "app-monitor",
  templateUrl: "./irr-project.component.html",
  styleUrls: ["./irr-project.component.scss"]
})
export class IrrProjectComponent implements OnInit, OnDestroy {
  private unsubscribe = new Subject<void>();
  init: boolean = true;
  treeNode: any[] = [];
  panelItem: any = {
    mode: "irrProject",
      title: '管理处',
    layerName: "zhikaikou"
  };
  monitorData: any = {
    show: false
  };
  chartData: any = {
    show: false
  };
  typeMapper: any = TypeMapper;
  dmArr: string[] = ['hh', 'gqdm', 'shg', 'psg', 'hd', 'yz', 'skswz', 'ylz', 'cyylz', 'sqz'];

  constructor(
    private mapUiService: MapUiService,
    private overlayService: OverlayService
  ) {}

  ngOnInit(): void {
    this.treeNode = TreeNode;
    this.mapUiService.modeChange.next("irrProject");
    this.mapUiService.treeNodeChange.next({
      treeNode: this.treeNode,
      initMap: true
    });
    this.mapUiService.panelChange.next(this.panelItem);
    this.mapUiService.entityClicked
      .pipe(takeUntil(this.unsubscribe))
      .subscribe(entity => {
        this.entityClicked(entity);
      });
    // this.mapUiService.entityHovered
    //   .pipe(takeUntil(this.unsubscribe))
    //   .subscribe(entity => {
    //     this.entityHovered(entity);
    //   });
    this.mapUiService.buildingSelected
      .pipe(takeUntil(this.unsubscribe))
      .subscribe(data => {
        // console.log(data);
        this.createOverlay(data);
      });
    this.mapUiService.searchSelected
      .pipe(takeUntil(this.unsubscribe))
      .subscribe(item => {
        this.onSearchSelect(item);
      });
    this.init = false;
  }

  ngOnDestroy(): void {
    this.overlayService.clear();
    this.unsubscribe.next();
    this.unsubscribe.complete();
  }

  entityClicked(entity) {
    console.log("----------entityClicked monitor-----------");
    if (!entity || !entity.layer || entity.layer == "boundary" || this.init) {
      this.mapUiService.twinkleOverlay.setPosition(null);
      this.mapUiService.showTwinkle = false;
      return;
    }

    const latLon = this.mapUiService.mapInstance.getPositionByEntity(
      entity.layer,
      entity.id
    );
    const layer = entity.layer.split("_").pop();
    this.createOverlay({ ...entity, latLon, layer });
  }

  entityHovered(entity) {}

  createOverlay(item): void {
    let overlayName;
    let title;
    let location;
    if (!item.overlayName) {
      title = item.properties && item.properties.name;
      switch (item.layer) {
        case "bengzhan":
          overlayName = DialogPumpComponent;
          title = title || item.pumpName;
          break;
        case "jinshuizha":
        case "jiezhizha":
        case "tuishuizha":
        case "zhikaikou":
          overlayName = DialogGateComponent;
          title = title || item.watergateCode;
          break;
        case 'db': // 地表取水口
        case 'dx': // 地下取水口
        case 'gy': // 工业取水口
        case 'ny': // 农业取水口
        case 'sh': // 生活取水口
          overlayName = DialogIntakeComponent;
          title = title || item.properties && item.properties.wiust_nm;
          break;
        case 'hd': // 河道水文站
        case 'yz': // 堰闸水文站
        case 'hh': // 黄河断面
        case 'skswz': // 水库水文站
        case 'gqdm': // 干渠断面
        case 'shg': // 山洪沟断面
        case 'psg': // 排水沟断面
        case 'ylz': // 雨量站
        case 'cyylz': // 常用雨量站
        case 'sqz': // 墒情站
          overlayName = DialogSectionComponent;
          title = title || item.stadiaName || item.properties && item.properties.Stadia_Name;
          break;
      }
      location = item.latLon
        ? item.latLon
        : item.geom
          ? [item.geom.lng, item.geom.lat]
          : [];
    } else {
      overlayName = item.overlayName;
      title = item.name;
      location = item.location;
    }

    if (!overlayName || !location.length) {
      return;
    }

    this.overlayService.clear();
    const h = this.mapUiService.mainCompEl.nativeElement.getBoundingClientRect()
      .height;
    const overlayHeight = item.layer == 'video' ? 650 : 450;
    const overlayPTop = Math.abs(h - overlayHeight - 50) / 2 + overlayHeight;
    this.mapUiService.mapInstance
      .flyTo(location as LatLonArray, {
        zoom: this.mapUiService.currentZoom > 12 ? this.mapUiService.currentZoom : 12,
        duration: 500,
        padding: [overlayPTop, 0, 0, 0]
      })
      .then(() => {
        this.overlayService.createOverlay(
          overlayName,
          {
            longitude: location[0],
            latitude: location[1],
            title,
            showLeader: true,
            width: item.layer == 'video' ? 1020 : 600,
            height: overlayHeight,
            offset: { x: 0, y: -15 },
            singleton: true,
            destroyOnClose: true,
            opacity: 0.8,
            data: item
          },
          true
        );
      });
  }

  onSearchSelect(item) {
    // console.log(item);
    let overlayName;
    switch (item.type) {
      case 1:
        overlayName = DialogPumpComponent;
        break;
      // case 2:
      //   overlayName = DialogSectionComponent;
      //   break;
      case 9:
      case 12:
        overlayName = DialogGateComponent;
        break;
      case 27:
      case 28:
        overlayName = DialogIntakeComponent;
        break;
      case 18:
      case 19:
      case 20:
      case 21:
      case 22:
      case 23:
      case 24:
      case 25:
      case 26:
        overlayName = DialogSectionComponent;
        break;
    }
    if (overlayName) {
      const location = item.longitude ? [item.longitude, item.latitude] : [item.geom.lng, item.geom.lat];
      this.createOverlay({
        ...item,
        name: item.buildName,
        code: item.buildCode,
        location,
        overlayName,
        layer: this.typeMapper[item.type]
      });
    }
  }
}
